using System;
using System.Collections.Generic;
using System.Threading;

namespace MEA.AE_BusinessLogic
{
	internal class ThreadManager
	{
		private Queue<ParameterizedThreadStart> threadQueue;

		private Queue<object> threadParameters;

		private Queue<string> threadNames;

		private Timer t_threadQueueProcess;

		private Thread thread_standard;

		public ThreadManager()
		{
			threadQueue = new Queue<ParameterizedThreadStart>();
			t_threadQueueProcess = new Timer(RunTask, null, 100, 100);
			threadParameters = new Queue<object>();
			threadNames = new Queue<string>();
		}

		public void AddTask(ParameterizedThreadStart task, object state)
		{
			lock (threadQueue)
			{
				if (task != null && !threadQueue.Contains(task))
				{
					threadQueue.Enqueue(task);
					threadParameters.Enqueue(state);
					threadNames.Enqueue(task.Method.ToString());
					Console.WriteLine(string.Format("Task Added: -{0}", task.Method));
				}
			}
		}

		private void RunTask(object o)
		{
			lock (threadQueue)
			{
				if (thread_standard == null)
				{
					if (threadQueue.Count > 0)
					{
						thread_standard = new Thread(threadQueue.Dequeue());
						thread_standard.Name = threadNames.Dequeue();
						thread_standard.IsBackground = true;
						thread_standard.Priority = ThreadPriority.AboveNormal;
						thread_standard.Start(threadParameters.Dequeue());
						Console.WriteLine(string.Format("Task Cnt: -{0}", threadQueue.Count));
					}
				}
				else if ((thread_standard.ThreadState == ThreadState.Stopped || thread_standard.ThreadState == ThreadState.Aborted) && threadQueue.Count > 0)
				{
					Console.WriteLine(string.Format("Task Cnt: -{0}", threadQueue.Count));
					thread_standard = new Thread(threadQueue.Dequeue());
					thread_standard.Name = threadNames.Dequeue();
					thread_standard.IsBackground = true;
					thread_standard.Priority = ThreadPriority.AboveNormal;
					thread_standard.Start(threadParameters.Dequeue());
				}
			}
		}

		public void AbortTasks(bool killThreadTimer)
		{
			lock (threadQueue)
			{
				threadQueue.Clear();
				threadParameters.Clear();
				threadNames.Clear();
			}
			if (thread_standard != null)
			{
				thread_standard.Abort();
			}
			if (killThreadTimer)
			{
				t_threadQueueProcess.Dispose();
			}
		}
	}
}
